const app = getApp()

Page({
  data: {
    certificateId: null,
    certificate: {},
    showVerifyDialog: false,
    verifyResult: {},
    loading: true
  },

  onLoad(options) {
    const { id } = options
    this.setData({ certificateId: id })
    this.loadCertificateDetail()
  },

  // 加载证书详情
  loadCertificateDetail() {
    wx.showLoading({ title: '加载中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/certificates/${this.data.certificateId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const certificate = res.data.data
          
          // 计算正确率
          certificate.accuracy = Math.round((certificate.correct_count / certificate.question_count) * 100)
          
          this.setData({ 
            certificate: certificate,
            loading: false
          })
          
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: certificate.title
          })
          
          wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载证书详情失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        wx.hideLoading()
      }
    })
  },

  // 下载证书
  downloadCertificate() {
    wx.showLoading({ title: '生成证书中...' })
    
    wx.request({
      url: `${app.globalData.baseUrl}/certificates/${this.data.certificateId}/download`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const { download_url } = res.data.data
          
          wx.downloadFile({
            url: download_url,
            success: (downloadRes) => {
              if (downloadRes.statusCode === 200) {
                wx.saveImageToPhotosAlbum({
                  filePath: downloadRes.tempFilePath,
                  success: () => {
                    wx.showToast({
                      title: '证书已保存到相册',
                      icon: 'success'
                    })
                  },
                  fail: (err) => {
                    console.error('保存证书失败:', err)
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail: (err) => {
              console.error('下载证书失败:', err)
              wx.showToast({
                title: '下载失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '下载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取下载链接失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 分享证书
  shareCertificate() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 验证证书
  verifyCertificate() {
    wx.showLoading({ title: '验证中...' })
    
    wx.request({
      url: `${app.globalData.baseUrl}/certificates/${this.data.certificateId}/verify`,
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          const verifyResult = res.data.data
          this.setData({
            verifyResult: verifyResult,
            showVerifyDialog: true
          })
        } else {
          wx.showToast({
            title: res.data.message || '验证失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('验证证书失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 关闭验证弹窗
  closeVerifyDialog() {
    this.setData({ showVerifyDialog: false })
  },

  // 分享给朋友
  onShareAppMessage() {
    const certificate = this.data.certificate
    return {
      title: `我在好爸爸100问获得了${certificate.title}证书！`,
      path: `/pages/certificate-detail/certificate-detail?id=${this.data.certificateId}`,
      imageUrl: certificate.qr_code_url
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    const certificate = this.data.certificate
    return {
      title: `我在好爸爸100问获得了${certificate.title}证书！`,
      imageUrl: certificate.qr_code_url
    }
  }
}) 